<template>
  <div class="my">
    <header>
      <h3 style="padding-left: 20px;">个人中心</h3>
    </header>
    <section>
      <!-- 个人信息 -->
      <div class="info">
        <!-- 头像 -->
        <div class="user-img">
          <div class="show-img">
            <van-image width="120px" height="120px" :src="src" />
          </div>
          <div class="upload-img">
            <van-uploader :after-read="afterRead" />
          </div>
        </div>

        <!-- 账号 -->
        <div class="user-name" style="text-align: left;">
          <p style="color: #666; margin-bottom: 10px;"> 账号: <span> {{ account }}</span></p>
          <p> 昵称: <span> {{ nickName }}</span></p>
          <div style="margin-top: 20px;">
            <van-button type="primary" plain size="small" @click="jumpToEditInfo">编辑资料</van-button>
            <van-button type="warning" plain size="small" @click="logout">退出登录</van-button>
          </div>
        </div>

      </div>

      <!-- 歌单 -->
      <div class="playlist">
        <!-- 标识 -->
        <div class="playlist-top">
          <span>歌单列表</span>

          <div>
            <van-icon name="add-o" size="30" color="#f50" @click="showInput" />
          </div>
        </div>
        <van-empty description="暂无歌单列表" v-if="arr.length == 0" />
        <!-- 列表 -->
        <ul class="playlist-body" v-else>
          <li v-for="item in arr" :key="item.playlist_id">
            <div @click="jumpPlayList(item.playlist_id, item.playlist_name)">
              <van-icon name="guide-o" size="24" color="#0C8BF3" />
              <span>{{ item.playlist_name }}</span>
            </div>
            <div>
              <van-icon name="edit" @click="editPlayListFn(item.playlist_id, item.playlist_name)" size="24"
                color="#ff5500" />
              <van-icon name="delete-o" @click="removePlayListFn(item.playlist_id)" size="24" color="#ff0000" />
            </div>
          </li>
        </ul>
      </div>

      <!-- <van-popover v-model="showPopover" trigger="click" :actions="actions" @select="onSelect">
        <template #reference>
          <van-icon name="ellipsis" size="30" color="#f50" />
        </template>
</van-popover> -->
      <!-- 其他 -->
      <div class="other-box">
        <!-- <router-link to="/list"><van-icon name="star-o" /> <span>我的收藏</span></router-link> -->
        <!-- <router-link to="/"><van-icon name="thumb-circle-o" /> <span>我的点赞</span></router-link> -->
        <!-- <router-link to="/"><van-icon name="user-o" /> <span>我的资料</span></router-link> -->
        <!-- <router-link to="/"><van-icon name="phone-circle-o" /><span>关于我们</span></router-link> -->
      </div>

    </section>


    <van-popup v-model="showPopup" position="bottom" :style="{ height: '30%' }">
      <div class="form">
        <div class="title">{{ label }}</div>
        <div>
          <input class="input" type="text" v-model="value" placeholder="请输入歌单名称" />
        </div>
        <div>
          <van-button type="info" @click="addPlayListFn">确认</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<style lang="less">
@import '../common/less/varible.less';

.my {
  padding-bottom: 80px;

  header {
    height: 50px;
    width: 100%;
    background-color: @bgColor;
    //text-align: center;
    line-height: 50px;
    font-size: 16px;
    color: #fff;
  }

  section {
    padding: 0 0 15px;

    .info {
      padding: 10px 20px;
      width: 100%;
      display: flex;
      border-bottom: 2px solid #ccc;
    }

    .user-img {
      width: 120px;
      height: 120px;
      // margin: 20px auto;
      position: relative;
      background-color: #ccc;
      border-radius: 10px;
      overflow: hidden;

      // 修改上传文件控件的外观
      .van-uploader__upload {
        width: 120px;
        height: 120px;
        border-radius: 10px;
        opacity: 0;
      }

      .show-img,
      .upload-img {
        position: absolute;
        top: 0;
        left: 0;
      }

      .upload-img {
        opacity: 0;
        z-index: 10
      }
    }

    .user-name {
      text-align: center;
      padding: 10px 15px;
      font-size: 18px;
    }

    .other-box {
      a {
        display: block;
        height: 44px;
        line-height: 44px;
        background-color: #f0f0f0;
        padding: 0 15px;
        margin-top: 10px;
        font-family: Arial, Helvetica, sans-serif;
        font-size: 16px;

        i {
          font-size: 24px;
          margin-right: 5px;
          vertical-align: middle;
        }

        span {
          vertical-align: middle;
        }
      }
    }
  }

  .playlist {
    padding: 10px 20px;

    .playlist-top {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 20px;
    }

    .playlist-body {
      li {
        width: 100%;
        display: flex;
        justify-content: space-between;
        font-size: 16px;
        font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
        padding: 30px 0px 20px 0px;
        border-bottom: 1px dashed #ccc;

        .van-icon {
          margin-right: 10px;
          font-size: 24px;
        }
      }
    }
  }

  .form {
    padding: 20px;

    .input {
      width: 100%;
      height: 50px;
      border: 1px solid #ccc;
      padding: 0 0 0 10px;
      margin: 10px 0px;
      font-size: 16px;
    }
  }

  .van-button--warning {
    border: 0px;
  }
}
</style>

<script>
import { Dialog, Toast } from 'vant';
import { host, uploadImg, setUserImg, userInfo, playListAdd, playListUser, playListRemove, playListModify, logged } from '../api/index'

export default {
  // 设置数据
  data() {
    return {
      nickName: '账号',
      account: "",
      src: '',
      actions: [
        { text: '编辑歌单' },
        { text: '删除歌单' },
      ],
      showPopover: false,
      showPopup: false,
      value: "",
      arr: [],
      label: "创建歌单",
      playlist_id: ""
    }
  },
  // 初始化钩子函数
  created() {
    //  获取用户身份
    let token = localStorage.getItem("UTOKEN");
    let imgUrl = localStorage.getItem("IMGURL");
    this.nickName = localStorage.getItem("UNICKNAME");
    this.src = host + imgUrl;
    //  判断是否登录
    if (token) {
      this.userInfoFn(token);
      this.playListUserFn(1, 30);
      logged({ token }).then(
        content => {
          console.log(content);
          if (content.code == -1) {
            Toast(content.msg)
            // localStorage.removeItem("UTOKEN")
            // localStorage.removeItem("IMGURL")
            // localStorage.removeItem("UNICKNAME")
            Dialog.confirm({
              confirmButtonColor: "#0c8bf3",
              title: '登录已经失效了',
              message: '是否跳转到登录页面吗?',
            })
              .then(() => {
                // on confirm （确定）
                // next({ path: '/login' })
                this.$router.push({ path: '/login' })
              })
              .catch(() => {
                // on cancel （取消）
                // next(false);
              });
          }
        }
      ).catch(err => console.log(err))
    }
  },
  // 访问这个组件之前的钩子函数
  beforeRouteEnter(to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不！能！获取组件实例 `this`
    // 因为当守卫执行前，组件实例还没被创建
    // 获取token
    let token = localStorage.getItem("UTOKEN");
    // 判断是有值
    if (token) {
      next(true);
    }
    else {
      Dialog.confirm({
        confirmButtonColor: "#0c8bf3",
        title: '您还没登录',
        message: '要跳转到登录页面吗?',
      })
        .then(() => {
          // on confirm （确定）
          next({ path: '/login' })
        })
        .catch(() => {
          // on cancel （取消）
          next(false);
        });
    }
  },

  // 编写方法
  methods: {
    // 跳转编辑资料
    jumpToEditInfo(){
      this.$router.push({ path: "/editinfo" })
    },
    // 跳转歌单页
    jumpPlayList(playlist_id, playList_name) {
      this.$router.push({ path: "/playlist", query: { playlist_id, playList_name } })
    },
    // 获取歌单列表
    async playListUserFn(page = 1, pageSize = 30) {
      let token = localStorage.getItem("UTOKEN");
      if (token == null) {
        Toast("请先登录");
        return false;
      }
      await playListUser({ token, page, pageSize }).then(
        content => {
          console.log(content)
          if (content.code == 200) {
            this.arr = content.result;
          }
        }
      ).catch(err => console.log(err))
    },
    // 创建歌单 | 编辑
    async addPlayListFn() {
      let playlist_name = this.value;
      let token = localStorage.getItem("UTOKEN");
      if (token == null) {
        Toast("请先登录");
        return false;
      }
      if (playlist_name == "") {
        Toast("输入框不能为空");
        return false;
      }

      if (this.label == "创建歌单") {
        await playListAdd({ playlist_name, token }).then(
          content => {
            console.log(content)
            if (content.code == 200) {
              this.playListUserFn(1, 30);
            }
          }
        ).catch(err => console.log(err))
      }
      else
        if (this.label == "编辑歌单") {
          await playListModify({ playlist_id: this.playlist_id, playList_name: this.value }).then(
            content => {
              // console.log(content);
              if (content.code == 200) {
                this.playListUserFn()
              }
              Toast(content.msg);
            }
          ).catch(err => console.log(err))
        }

      // 关闭弹窗
      this.showPopup = false;
      this.value = "";
    },
    showInput() {
      this.showPopup = true;
      this.label = "创建歌单"
    },
    // 编辑歌单
    async editPlayListFn(playlist_id, playList_name) {
      this.label = "编辑歌单"
      this.showPopup = true;
      this.value = playList_name;
      this.playlist_id = playlist_id;
    },
    async removePlayListFn(playlist_id) {
      Dialog.confirm({
        confirmButtonColor: "#0c8bf3",
        title: '您确定要删除',
        message: '这个歌单吗?',
      })
        .then(async () => {
          await playListRemove({ playlist_id }).then(
            content => {
              console.log(content);
              if (content.code == 200) {
                this.playListUserFn()
              }
              Toast(content.msg);
            }
          ).catch(err => console.log(err))
        })
        .catch(() => {
          // on cancel （取消）
        });

    },
    onSelect(action) {
      console.log(action.text)
    },
    async afterRead(data) {
      // 此时可以自行将文件上传至服务器
      console.log(data);
      if (data) {
        // 把base64格式的图片字符串赋值给src变量
        // this.src = data.content;
        // 获取用户身份
        let token = localStorage.getItem("UTOKEN");
        if (token) {
          let fd = new FormData()
          fd.append("photo", data.file);
          await uploadImg(fd).then(async content => {
            console.log(content)
            let { code, picUrl } = content;
            if (code == 200) {
              // picUrl
              this.src = host + picUrl;
              await setUserImg({ token: token, imgUrl: picUrl }).then(content => {
                console.log(content);
                if (content.code == 200) {
                  localStorage.setItem("IMGURL", picUrl);
                }
              })
                .catch(err => console.log(err))
            }
          })
            .catch(err => console.log(err))
        }
      }
    },
    // 退出登录
    logout() {
      // 先给用户做弹窗反馈
      Dialog.confirm({
        confirmButtonColor: "#0c8bf3",
        message: '您要退出登录吗',
        title: "提示",
      })
        .then(() => {
          // on close
          localStorage.removeItem("UTOKEN");
          localStorage.removeItem("IMGURL");
          localStorage.removeItem("UNICKNAME");
          setTimeout(() => {
            // 跳转登录页
            this.$router.push({ path: '/login' })
          }, 150)
        })
        .catch(
          err => {
            console.log(err);
          }
        )
    },
    async userInfoFn(token) {
      // 赋值
      //  let token = localStorage.getItem("UTOKEN");
      // 为了减少报错。多加一个判断
      if (token) {
        await userInfo({ token }).then(
          content => {
            console.log(content);
            let { code, result } = content;
            if (code == 200) {
              this.nickName = result[0].nickName;
              this.account = result[0].account;
              this.token = token;
            }
          }
        ).catch(err => console.log(err))
      }
    }
  }
}
</script>